package com.example.mapsapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.AsyncTask;
import android.util.Log;
// https://maps.googleapis.com/maps/api/place/textsearch/xml?query=restaurants+in+Sydney&sensor=true&key=AddYourOwnKeyHere
public class GetPlacesTask extends AsyncTask<String, String, ArrayList<Place>>{
	public  String requesturl="https://maps.googleapis.com/maps/api/place/textsearch/xml?query=";
	public String secon = "&sensor=true&key=AIzaSyCGZcjU78G0JNhjNBGkPRnbFa-SA6WqCvs";
	public  ArrayList<Place> posi;
	@Override
	protected ArrayList<Place> doInBackground(String... params) {
		      XmlPullParser batman = tryDown(params[0]);
		 try {
			 Log.i("Request failed5", "these is it  in background");
			posi = trygeMessage(batman);
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			 Log.i("Request failed5", "these is it  in background");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			 Log.i("Request failed5", "these is it  in background");
		}
		return posi;
	}

	
	private XmlPullParser tryDown(String plate) {
		try{
       	   StringBuilder  builder = new StringBuilder(requesturl);
       	   builder.append(plate);
       	    builder.append("+in+"+SearchPlaces.latitude+","+SearchPlaces.longitude);
       	   builder.append("&radius=500");
       	   builder.append(secon);
       	 System.out.println(builder.toString()+"this shoud be");
	       URI url  = new URI(builder.toString());
	       DefaultHttpClient client = new DefaultHttpClient();
	       HttpGet method = new HttpGet(url);
	       HttpResponse res = client.execute(method);      
		  XmlPullParser superman = XmlPullParserFactory.newInstance().newPullParser();
		  superman.setInput(new InputStreamReader(res.getEntity().getContent()));
		  Log.i("Request failed3", "ok in first method");
		   return superman;
		}
		catch(XmlPullParserException e)
		{
			 
			Log.i("Request failed1", e.toString());
		}
		catch(IOException e)
		{
			
			Log.i("Request failed2", e.toString());
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			Log.i("Request failed3", e.toString());
			//e.printStackTrace();
			
		}
		
		return null;
		 
	}
	
private ArrayList<Place> trygeMessage(XmlPullParser batman) throws XmlPullParserException, IOException{
		
        ArrayList<Place> results = new ArrayList<Place>();
		String []  wonderwoman = new String[40];
      
		    int eventType;			 
			eventType = batman.getEventType();
			String currentTag = null;
	        String  name = "";
	        double lat  =0.0;
	        double lng = 0.0;
	        String icon = null;
	        String address = null;
	        boolean done = false;
	        String TagTest = null;
	        int i  = 0;
	        while (eventType != XmlPullParser.END_DOCUMENT) {
	        	    
	        	     
	            if(eventType == XmlPullParser.START_DOCUMENT) {
	                 
	                System.out.println("Start document");
	            } else if(eventType == XmlPullParser.END_DOCUMENT) {
	            	
	                System.out.println("End document");
	            } else if(eventType == XmlPullParser.START_TAG) {
	            	TagTest = batman.getName();
	                System.out.println("Start tag "+batman.getName());
	            } else if(eventType == XmlPullParser.END_TAG) {
	            	   TagTest =" ";
	            	 if(batman.getName().equals("result")){
	            		 System.out.println("Do i get Result "+batman.getName());
	                      Place ironMan = new Place(name,lat,lng,address,icon); 
	                      results.add(ironMan);
	            	  }
	                System.out.println("End tag "+batman.getName());
	            } else if(eventType == XmlPullParser.TEXT) {
	            	if (TagTest.equals("formatted_address"))
	            	  {
	            		address = batman.getText();
	            	  }
	            	else if (TagTest.equals("lat"))
	            	{
	            		lat = Double.parseDouble(batman.getText());
	            	}
	            	else if(TagTest.equals("lng"))
	            	{
	            		lng = Double.parseDouble(batman.getText());
	            	}
	            	else if(TagTest.equals("icon"))
	            	{
	            		icon = batman.getText();
	            	}
	            	else if(TagTest.equals("name"))
	            	{
	            		name = batman.getText();
	            	}
	            	   
	                 
	            }
	             i++;
	            eventType = batman.next();
	           }     
	       
	        
	          
	        return (ArrayList<Place>)results;
	}

    @Override
	protected void onPostExecute(ArrayList<Place> result)
	{
    	LatLng lati;
    	for(Place wummie:result)
		{    lati = new LatLng(wummie.getLatitude(),wummie.getLongitude());
		    System.out.println(wummie.getName()+"hither"+wummie.getAddress());
			 SearchPlaces.mapes.addMarker(new MarkerOptions().position(lati).title(wummie.getName()+"   address= " +wummie.getAddress()));
			 
		}
		 CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(SearchPlaces.lati, 14);
		 System.out.println("i am here3");
		 SearchPlaces.mapes.animateCamera(cameraUpdate);
  
	}

}
